package com.jftone.bh.app.data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jftone.bh.app.config.SysConst;
import com.jftone.bh.app.model.SysParam;
import com.jftone.bh.app.service.SysParamService;
import org.apache.log4j.Logger;
import org.jftone.component.BeanContext;
import org.jftone.data.redis.RedisTemplate;
import org.jftone.exception.ComponentException;
import org.jftone.util.DataMap;
import org.jftone.util.IData;


public final class StaticInfoQry {	
	
	private static Logger logger = Logger.getLogger(StaticInfoQry.class);
	
	private static final String SYS_PARAM = "BH_SYS_PARAM";
	
	/**
	 * 创建静态参数缓存
	 * @throws Exception 
	 */
	public static void createCache() throws Exception{
		String superCode = SysConst.ROOT_CODE;
		try {
			RedisTemplate cache = BeanContext.getBean(RedisTemplate.class);
			List<SysParam> paramList = queryStaticInfo(superCode);
			if(null != paramList && paramList.size()>0){
				String key = null;
				for(SysParam param : paramList){
					key = param.getDataCode();
					cache.put(SYS_PARAM+"_"+key, queryStaticInfo(key));
				}
			}
		} catch (ComponentException e) {
			throw new Exception("加载系统静态数据错误"+e.getMessage(), e);
		}
	}
	
	private static List<SysParam> queryStaticInfo(String superCode) throws Exception{
		List<SysParam> list  = null;
		try {
			SysParamService service = BeanContext.getBean(SysParamService.class);
			IData<String, Object> inData = new DataMap<String, Object>();
			inData.put("dataType", superCode);
			list = service.querySysParam(inData);
		} catch (ComponentException e) {
			throw new Exception("查询系统静态数据错误"+e.getMessage(), e);
		}
		return list;
	}
	
	/**
	 * 获取参数名称
	 * @param dataCode
	 * @return
	 * @throws Exception 
	 */
	public static final String getParamName(String dataType, String dataCode){
		String paramName = "";
		List<SysParam> list = getParams(dataType);
		for(SysParam param : list){
			if(dataCode.equals(param.getDataCode())){
				paramName = param.getDataName();
				break;
			}
		}
		return paramName;
	}

	/**
	 * 获取List对象集合参数
	 * @param dataType
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static final List<SysParam> getParams(String dataType){
		List<SysParam> list  = null;
		String key = SYS_PARAM+"_"+dataType;
		try {
			RedisTemplate cache = BeanContext.getBean(RedisTemplate.class);
			list = cache.get(key, ArrayList.class);
			if(null==list){
				list = queryStaticInfo(dataType);
				cache.put(key, list);
			}
		} catch (Exception e) {
			logger.error("获取缓存系统静态数据错误"+e.getMessage(), e);
		}
		return list;
	}
	
	/**
	 * 返回Map对象集合参数
	 * @param dataType
	 * @return
	 * @throws Exception 
	 */
	public static final Map<String, String> getParamMap(String dataType){
		Map<String, String> data = new HashMap<String, String>();
		List<SysParam> list = getParams(dataType);
		for(SysParam param : list){
			data.put(param.getDataCode(), param.getDataName());
		}
		return data;
	}
}
